/*
 * @Author: fanjs
 * @Date: 2025-04-09 17:48:04
 * @Description: 邮箱配置表单
 */
import React, { useImperativeHandle, useState } from 'react';
import type { EmailItem } from '../types';
import { Textarea, Form, RadioGroup, Radio, cn, Input, Select, SelectItem, Tooltip } from "@heroui/react";
import { protocols, mails } from '@/constants/common';
import { validateConfigForm } from '../utils/validation';
import { SvgIcon } from '@/components/SvgIcon';

// Select, SelectItem,
interface ConfigFormProps {
  rowData: EmailItem;
  ref: React.ForwardedRef<{ fetchData: () => Partial<EmailItem> | null, reset: () => void }>;
  isLoading: boolean;
  isDisabled: boolean;
}

export const CustomRadio = (props: any) => {
  const { children, ...otherProps } = props;
  return (
    <Radio
      {...otherProps}
      className="w-[32%] max-w-[999px]"
      classNames={{
        base: cn(
          "inline-flex m-0 bg-default-200/30 hover:bg-default-200/80 items-center justify-between",
          "flex-row-reverse cursor-pointer rounded-lg gap-2 px-3 py-2 border-2 border-transparent",
          "data-[selected=true]:border-secondary",
        ),
      }}
    >
      {children}
    </Radio>
  );
};

const ConfigForm: React.FC<ConfigFormProps> = ({ ref, rowData, isLoading, isDisabled }) => {
  const formRef = React.createRef<HTMLFormElement>();

  const [formData, setFormData] = useState<Partial<EmailItem>>(
    rowData?.id ? {
      ...rowData,
    } : {
      protocol: 'SMTP', // 协议
      company: '163.com', // 邮箱类型
      email_account: '', // 邮箱
      pass: '', // 密钥
    });

  // 发送数据
  const emitData = () => {
    if (!validateConfigForm(formData)) return null;
    const sendData: Partial<EmailItem> = {
      protocol: formData.protocol,
      company: formData.company,
      email_account: formData.email_account,
      pass: formData.pass,
    }
    if (formData.id) sendData.id = formData.id;
    return sendData;
  };

  // 将提交方法暴露给父组件
  useImperativeHandle(ref, () => {
    return {
      fetchData: emitData,
      reset: () => {
        formRef.current?.reset();
      }
    };
  });

  // 字段变更处理
  const handleChange = (field: keyof EmailItem, value: string | number) => {
    setFormData(prev => {
      const updated = { ...prev, [field]: value };
      return updated;
    });
  };

  return (
    <Form ref={formRef} className="w-full gap-4">
      <RadioGroup isRequired isDisabled={isDisabled || isLoading} color='secondary' className='flex-nowrap w-full text-sm' size="sm" value={formData.protocol}
        onValueChange={(value: any) => handleChange('protocol', value)}
        orientation="horizontal">
        {protocols.map((mail: { key: string, label: string, disabled?: boolean }) => (
          <CustomRadio value={mail.key} description={`开启 ${mail.label} 服务`}>{mail.label}</CustomRadio>
        ))}
      </RadioGroup>

      <Select
        isRequired
        selectedKeys={new Set([formData.company]) as any}
        onSelectionChange={(keys: any) => handleChange('company', Array.from(keys)[0] as string)}
        label="邮箱类型"
        radius="lg"
        isDisabled={isDisabled || isLoading}
      >
        {mails.map((mail: { key: string, label: string, disabled?: boolean }) => (
          <SelectItem key={mail.key} isDisabled={mail.disabled}>{mail.label}</SelectItem>
        ))}
      </Select>
      <Input
        isRequired
        value={formData.email_account}
        onValueChange={(value: any) => handleChange('email_account', value)}
        label="邮箱地址"
        type="email"
        isDisabled={isDisabled || isLoading}
      />
      <Textarea isRequired value={formData.pass} onValueChange={(value: any) => handleChange('pass', value)} minRows={10} isDisabled={isDisabled || isLoading} label="将安全密钥粘贴至此并校验" />
      <Tooltip content={
        <div className="px-1 py-2">
          <div className="text-small font-bold">按以下流程获取安全密钥</div>
          {formData.company === '163.com' && (
            <div>
              <div className="text-tiny mt-2">1. 访问邮箱 <a href="https://mail.163.com/" className='text-secondary' target="_blank" rel="noreferrer">https://mail.163.com/</a>，登录邮箱</div>
              <div className="text-tiny mt-2">2. 点击「设置」，选择「SMTP/POP3/IMAP」</div>
              <div className="text-tiny mt-2">3. 开启一个协议，发件默认SMTP（包含即可）</div>
              <div className="text-tiny mt-2">4. 弹窗中不下载，选择继续开启，点击后生成授权码</div>
              <div className="text-tiny mt-2">5. 将授权码粘贴到安全密钥框中</div>
            </div>
          )}
          {formData.company === 'qq.com' && (
            <div>
              <div className="text-tiny mt-2">1. 访问邮箱 <a href="https://mail.qq.com/" className='text-secondary' target="_blank" rel="noreferrer">https://mail.qq.com/</a>，登录邮箱</div>
              <div className="text-tiny mt-2">2. 点击「设置」，在顶部邮箱设置中，选择「账号」</div>
              <div className="text-tiny mt-2">3. 页面中找到「POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务」栏目</div>
              <div className="text-tiny mt-2">4. 点击「管理服务」，生成授权码</div>
              <div className="text-tiny mt-2">5. 将授权码粘贴到安全密钥框中</div>
            </div>
          )}

        </div>
      } placement="top">
        <div className='flex-y-center h-8'>
          <SvgIcon icon="line-md:question-circle" className='text-lg text-secondary mr-1' />
          <span className='text-secondary text-sm'>获取安全密钥</span>
        </div>
      </Tooltip>
    </Form>
  );
};

export default ConfigForm;
